from aiogram import F, Router, types
from aiogram.fsm.context import FSMContext

from database import models
from tg_bot.filters.user_filter import IsActive
from tg_bot.handlers.user.personal_account import personal_account
from tg_bot.keyboards import inline, callback_factory as cf
from tg_bot.services.text import not_correct_input
from tg_bot.states.user import PersonalAccount
from tg_bot.states.user import VoucherActivation

router = Router()
router.message.filter(IsActive())
router.callback_query.filter(IsActive())


@router.callback_query(cf.ActionCall.filter(
    F.action == 'voucher_activation'
), PersonalAccount.main)
async def voucher_activation_call(call: types.CallbackQuery,
                                  state: FSMContext):
    """
    Активация сценария по вводу ваучера через инлайн кнопку.

    ----
    :param call: Callback.
    :param state: State.
    :return:
    """
    text = 'Введите ваучер: '
    key = await inline.cancel()
    await call.message.answer(text, reply_markup=key)
    await state.set_state(VoucherActivation.voucher_enter)


@router.callback_query(cf.ActionCall.filter(
    F.action == 'cancel'
), VoucherActivation())
async def cancel_voucher_activation_call(call: types.CallbackQuery,
                                         state: FSMContext):
    """
    Отмена сценария по вводу ваучера.

    ----
    :param call: Callback.
    :param state: State.
    :return:
    """
    await state.set_state(PersonalAccount.main)
    await call.answer('Отменил активацию ваучера!', show_alert=True)
    await call.message.delete()


@router.message(VoucherActivation.voucher_enter)
async def voucher_entering_message(message: types.Message,
                                   state: FSMContext,
                                   user: models.TgUser):
    """
    Проверка ваучера и его активация.

    ----
    :param message: Сообщение тг с ваучером.
    :param state: Состояние пользователя.
    :param user: Пользователь.
    :return:
    """
    if voucher := models.Voucher.objects.filter(voucher=message.text).first():
        voucher_status, comment = voucher.is_able_to_activate(user)
        if voucher_status:
            voucher.activate(user)
            user.balance += voucher.voucher_sum
            user.save('Активация ваучера!')
            await personal_account(message, state, user)
        else:
            await not_correct_input(message, comment)
    else:
        await not_correct_input(message, 'Не нашел такого ваучера!')
